package com.buli.blmall.admin.common.service;

import com.buli.blmall.admin.common.domain.WxQrCode;
import com.buli.blmall.admin.common.domain.WxTicket;
import com.buli.blmall.admin.consts.WxConsts;
import com.buli.blmall.admin.utils.WeixinUtil;
import com.buli.blmall.admin.core.cache.RedisClient;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author xiang.gao
 * @date 2025/2/18 17:22
 */
@Slf4j
@Service
@AllArgsConstructor
public class WeixinService {

    private final RedisClient redisClient;

    private String buildQrCodeImg(String ticket) {
        return WxConsts.QR_CODE_IMAGE_URL.concat("?ticket=").concat(ticket);
    }

    /**
     * 获取微信二维码
     * @param sceneId
     * @return
     */
    public WxQrCode getWxQrCode(String sceneId) {
        if (StringUtils.isBlank(sceneId)) {
            sceneId = UUID.randomUUID().toString();
            log.info("sceneId为空，生成随机sceneId={}", sceneId);
        }
        WxTicket wxTicket = redisClient.getValue(WxConsts.SCENE_KEY + sceneId);
        if (wxTicket != null) {
            return new WxQrCode(sceneId, buildQrCodeImg(wxTicket.getTicket()));
        }
        log.info("创建微信二维码,sceneId={}", sceneId);
        wxTicket = WeixinUtil.getWxTicket(sceneId);
        redisClient.setValue(WxConsts.SCENE_KEY + sceneId, wxTicket, wxTicket.getExpire_seconds());
        return new WxQrCode(sceneId, buildQrCodeImg(wxTicket.getTicket()));
    }

    /**
     * 扫描登录码
     * @param sceneId
     * @return
     */
    public String pullQrCode(String sceneId) {
        log.info("轮询是否登录,sceneId={}", sceneId);
        WxTicket wxTicket = redisClient.getValue(WxConsts.SCENE_KEY + sceneId);
        if (wxTicket == null) {
            return null;
        }
        String value = redisClient.getValue(WxConsts.TICKET_KEY + wxTicket.getTicket());
        if (value == null) {
            return WxConsts.PULL_WAITING;
        }
        return value;
    }

    /**
     * 扫码二维码
     * @param ticket
     * @param openId
     * @return
     */
    public void scanQrCode(String ticket, String openId) {
        String value = redisClient.getValue(WxConsts.TICKET_KEY + ticket);
        if (StringUtils.isBlank(value)) {
            redisClient.setValue(WxConsts.TICKET_KEY + ticket, openId);
        }
    }

}
